// author fucaihe@pryun.com.cn
// create time 2018-05-093 15:22:49
// struct 帮助工具

package kit

import (
	"reflect"
	"strings"
)

// Struct2Map struct转map
func Struct2Map(c interface{}, tag string) map[string]interface{} {
	t := reflect.TypeOf(c)
	v := reflect.ValueOf(c)

	var data = make(map[string]interface{})
	for i := 0; i < t.NumField(); i++ {
		tagVal := t.Field(i).Tag.Get(tag)
		if !strings.Contains(tagVal, ",") {
			data[tagVal] = v.Field(i).Interface()
			continue
		}
		tagArr := strings.Split(tagVal, ",")
		if strings.TrimSpace(tagArr[1]) == "omitempty" {
			switch vtype := v.Field(i).Interface().(type) {
			case string:
				if strings.TrimSpace(vtype) != "" {
					data[strings.TrimSpace(tagArr[0])] = v.Field(i).Interface()
				}
			case int:
				if vtype != 0 {
					data[strings.TrimSpace(tagArr[0])] = v.Field(i).Interface()
				}
			default:
				if vtype != nil {
					data[strings.TrimSpace(tagArr[0])] = v.Field(i).Interface()
				}
			}
			continue
		}

		data[strings.TrimSpace(tagArr[0])] = v.Field(i).Interface()
	}
	return data
}
